package com.pic4493.app;

import java.util.ArrayList;

import org.json.JSONArray;

import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;

import com.pic4493.adapter.AdpList_WallPaper;
import com.pic4493.base.BaseUITopBar;
import com.pic4493.comm.Session;
import com.pic4493.entities.DJson;
import com.pic4493.entities.EPhoto;
import com.pic4493.net.NetClientJ;
import com.pic4493.utils.UtiDialog;
import com.pic4493.utils.UtiImage;
import com.ppcodes.imageloader.core.DisplayImageOptions;
import com.ppcodes.views.pulltorefresh.library.PullToRefreshBase;
import com.ppcodes.views.pulltorefresh.library.PullToRefreshStaggeredGridView;
import com.ppcodes.views.pulltorefresh.library.PullToRefreshBase.Mode;
import com.ppcodes.views.staggeredgridview.StaggeredGridView;

public class UIWallPaper extends BaseUITopBar
{
   private PullToRefreshStaggeredGridView mGridView;
   private LayoutInflater mInflater;
   private int mCurrentIndex = 1;
   private int mPageCount;
   private ArrayList<Integer> mLoadedIndex;
   private boolean mIsPullToRefresh = false;

   private ArrayList<EPhoto> mList;
   private AdpList_WallPaper mAdp;

   private void initView()
   {
	  mInflater = LayoutInflater.from(mContext);
	  mGridView = (PullToRefreshStaggeredGridView) findViewById(R.id.uiwallpaper_list);
	  View footView = mInflater.inflate(R.layout.layout_loading_footer, null);// 加载时显示的
	  mGridView.getRefreshableView().setFooterView(footView);
	  mGridView.getRefreshableView().setColumnCount(2);
	  mGridView.setMode(Mode.PULL_FROM_START);
   }

   private void initEvent()
   {
	  // 下拉触发的事件
	  mGridView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener<StaggeredGridView>()
	  {
		 @Override
		 public void onRefresh(PullToRefreshBase<StaggeredGridView> refreshView)
		 {
			mIsPullToRefresh = true;
			initData();
		 }
	  });
	  // 滑到最下面加载更多数据的事件
	  mGridView.setOnLoadmoreListener(new StaggeredGridView.OnLoadmoreListener()
	  {
		 @Override
		 public void onLoadmore()
		 {
			if (mCurrentIndex < mPageCount)
			{
			   loadMoreData();
			}
			else
			{
			   mGridView.onLoadComplete();
			   mAdp.notifyDataSetChanged();
			   UtiDialog.getInstance().ShowToastInfoShort(mContext, "没有更多的数据了");
			}
		 }
	  });
	  mAdp = new AdpList_WallPaper(mContext, new AdpList_WallPaper.OnClickEvent()
	  {
		 @Override
		 public void Do(int position, View v)
		 {
            executeAsyncTask("saveWallPaper",new Object[]{position});
		 }
	  });
   }

   private void initData()
   {
	  mCurrentIndex = 1;
	  mAdp.cleanData();
	  mLoadedIndex = new ArrayList<Integer>();
	  executeAsyncTask("initData");
   }

   private void loadMoreData()
   {
		 mCurrentIndex++;
		 if (!isLoadedThisPage(mCurrentIndex))// 此页没有被加载过
		 {
			executeAsyncTask("loadData");
		 }
   }

   private boolean isLoadedThisPage(int index)
   {
	  if (-1 == mLoadedIndex.indexOf(index))
	  {
		 return false;
	  }
	  else
	  {
		 return true;
	  }
   }

   @Override
   protected void onCreate(Bundle savedInstanceState)
   {
	  setContentView(R.layout.uiwallpaper);
	  super.onCreate(savedInstanceState);
	  setTitle("精选壁纸");
	  initView();
	  initEvent();
	  initData();
   }

   @Override
   public void onAsyncTaskStart(String taskName, Object[] params)
   {
	  if ("initData".equals(taskName))
	  {
		 if (!mIsPullToRefresh)
		 {
			UtiDialog.getInstance().ShowLoadingDialogNoTitle(mContext, "加载中...");
		 }
	  }
	  else if ("saveWallPaper".equals(taskName))
	  {
		 UtiDialog.getInstance().ShowLoadingDialogNoTitle(mContext, "保存中...");
	  }
   }

   @Override
   public Object onAsyncTaskInBackground(String taskName, Object[] params) throws Exception
   {
	  try
	  {
		 if ("loadData".equals(taskName) || "initData".equals(taskName))
		 {
			return NetClientJ.GetWallPaperList(mCurrentIndex);
		 }
		 else if ("saveWallPaper".equals(taskName))
		 {
			Session.getInstance().picWallPaper=UtiImage.getImage(((EPhoto) mAdp.getItem(Integer.valueOf(params[0].toString()))).getUrl());
			UtiImage.saveWallPaper(Session.getInstance().picWallPaper);
			return "0";
		 }
	  }
	  catch (Exception e)
	  {
		 Log.d("ERROR", "UIWallPaper_onAsyncTaskInBackground(taskName, params) " + e);
	  }

	  return null;
   }

   @Override
   public void onAsyncTaskEnd(String taskId, String taskName, Object[] params, Object result)
   {
	  UtiDialog.getInstance().DismissLoadingDialog();
	  try
	  {
		 if (result != null)
		 {
			if ("saveWallPaper".equals(taskName))//保存壁纸
			{
               if(result.toString().equals("0"))
               {
            	  UtiDialog.getInstance().ShowToastInfoShort(mContext, "壁纸设置成功");
               }
			}
			else//其他任务
			{
			   DJson data = (DJson) result;
			   if (!data.getHead().hasError())
			   {
				  if ("initData".equals(taskName) || "loadData".equals(taskName))
				  {
					  mPageCount = data.getHead().getPageCount();
					  JSONArray photos = data.getBody().optJSONArray("wallpaper");
					 if (photos != null && photos.length() > 0)
					 {
						mList = new ArrayList<EPhoto>();
						EPhoto photo = null;
						for (int i = 0; i < photos.length(); i++)
						{
						   photo = new EPhoto();
						   photo.setId(photos.optJSONObject(i).optString("wid"));
						   photo.setUrl(photos.optJSONObject(i).optString("bigpic"));
						   photo.setThumbnailUrl(photos.optJSONObject(i).optString("thumbnail"));
						   photo.setThumbnailHeight(photos.optJSONObject(i).optInt("thum_height", 0));
						   photo.setThumbnailWidth(photos.optJSONObject(i).optInt("thum_width", 0));
						   mList.add(photo);
						}

						mAdp.addItem(mList);
						if ("initData".equals(taskName))
						{
						   mGridView.setAdapter(mAdp);
						}
						 if (mPageCount == 1)// 如果只有一页数据,也不显示最下面的loading
						 {
							mGridView.onLoadComplete();
						 }
						mAdp.notifyDataSetChanged();
						mLoadedIndex.add(mCurrentIndex);// 将此页加入已读页码列表
					 }
					 else
					 {
						 if (mList.size() == 0)
						 {
							UtiDialog.getInstance().ShowToastInfoShort(mContext, "暂无数据");
							finish();
						 }
						 else
						 {
							mGridView.onLoadComplete();
							mAdp.notifyDataSetChanged();
							if (mAdp.getCount() == 0)
							{
							   UtiDialog.getInstance().ShowOKAlertDialogEX(mContext, "提示", "暂无数据", new DialogInterface.OnClickListener()
							   {
								  @Override
								  public void onClick(DialogInterface dialog, int which)
								  {
									 finish();
								  }
							   });
							}
						 }
					 }
					 if (mIsPullToRefresh)
					 {
						mGridView.onRefreshComplete();
						mIsPullToRefresh = false;
					 }
				  }
			   }
			   else
			   {
				  UtiDialog.getInstance().ShowToastInfoShort(mContext, data.getHead().getRspMsg());
			   }
			}
		 }
		 else
		 {
			UtiDialog.getInstance().ShowToastInfoShort(mContext, "网络异常请稍候再试");
		 }
	  }
	  catch (Exception e)
	  {
		 Log.d("ERROR", "UIDestopList_onAsyncTaskEnd(taskId, taskName, params, result) " + e);
	  }
   }
}
